<template>
  <div class="gk-layout-container">
    <div class="gk-layout-header">
      <!--工具栏-->
      <s-query perms="material:item" @click="findPage" add=true @addClick="handleAdd">
        <el-form-item>
          <el-input v-model="filters.name" :placeholder="$t('item.please enter')"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="filters.code" placeholder="请输入编码"></el-input>
        </el-form-item>

      </s-query>

      <s-reflash excel="true" @exportExcel="exportExcel">

        <el-tooltip content="导入" placement="top">
          <el-button icon="fa fa-database" @click="importExcel" />
        </el-tooltip>
      </s-reflash>

    </div>


    <div class="gk-layout-main">
      <my-table :data="pageResult.content" :loading="loading">
        <el-table-column :label="$t('action.desc')" width="50" header-align="center" align="center">
          <template slot-scope="scope"> {{ scope.$index + 1 }} </template>
        </el-table-column>
        <column prop="code" width="150" label="编码" />
        <column prop="fenlei" width="150" label="物料类型" :formatter="fenleiFormat" />
        <el-table-column header-align="center" align="center" label="名称 / 规格">
          <template slot-scope="scope">
            <span style="margin-right: 1px">{{ scope.row.name }}</span>
            <span style="color:red; font-size:16px;">/</span>
            <span style="margin-left: 1px">{{ scope.row.gg }}</span>
          </template>
        </el-table-column>
      <column prop="classifyId" width="150" label="分类" :formatter="selectionClassTypesFormats" />
        

        <column prop="orderNo" width="80" label="排序" />
        <!--
        
       <el-table-column header-align="center" align="center" prop="active" key="active" label="状态" :formatter="activeStatusFormat"/>
        
        -->


        <el-table-column header-align="center" align="center" :label="$t('action.operation')" width="200">
          <template slot-scope="scope">
            <kt-button :label="$t('item.restore')" v-if="scope.row.active == '0'" perms="material:item:restore"
              @click="handleRestore(scope.$index, scope.row)" />
            <kt-delete-button v-if="scope.row.active == '1'" perms="material:item:Disable"
              @click="handleDisable(scope.$index, scope.row)" />
            <kt-button :label="$t('action.edit')" perms="material:item:edit"
              @click="handleEdit(scope.$index, scope.row)" />
            <kt-button label="同步" v-if="false" perms="material:item:edit"
              @click="handleInitArea(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </my-table>
    </div>
    <!--分页栏-->
    <div class="toolbar gk-layout-footer" style="padding:10px;">
      <el-pagination layout="total, prev, pager, next, jumper" @current-change="findPage" :current-page="filters.pageNum"
        :page-size="filters.pageSize" :total="pageResult.totalSize" style="float:right;">
      </el-pagination>
    </div>
    <!-- EXCEL导入 -->
    <upload-file :key="componentKey" :UpLoadFileVisible="UpLoadFileVisible" @ImportExcelData="ImportExcelData"
      @cancel="cancel" :PercentageValue="this.percentageValue"></upload-file>

    <!--新增编辑界面-->
    <el-dialog :title="operation ? '物料 —— 新增' : '物料 —— 编辑'" width="40%" :visible.sync="dialogVisible"
      :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="90px" :rules="dataFormRules" ref="dataForm" :size="global.gSize"
        label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="dataForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="编码" prop="code">
          <el-input v-model="dataForm.code" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="产品规格" prop="gg">
          <el-input v-model="dataForm.gg" auto-complete="off"></el-input>
        </el-form-item>

        <s-dict-form name="fenlei"   v-model="dataForm.fenlei" />





        <s-dict-form name="units" v-model="dataForm.unit" />


        <el-form-item label="上限" prop="limitMax">
          <el-input v-model="dataForm.limitMax" auto-complete="off" placeholder=""
            onkeyup="value=value.replace(/[^0-9]/g,'')" clearable></el-input>
        </el-form-item>
        <el-form-item label="下限" prop="limitMin">
          <el-input v-model="dataForm.limitMin" auto-complete="off" placeholder=""
            onkeyup="value=value.replace(/[^0-9]/g,'')" clearable></el-input>
        </el-form-item>

        <el-form-item :label="$t('item.classifyId')" prop="classifyId">
          <el-select v-model="dataForm.classifyId" placeholder="请选择" style="width: 100%;" clearable filterable>
            <el-option v-for="item in classTypes" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderNo">
          <el-input v-model="dataForm.orderNo" auto-complete="off" placeholder=""
            onkeyup="value=value.replace(/[^0-9]/g,'')" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="global.gSize" @click.native="dialogVisible = false">{{ $t('action.cancel') }}</el-button>
        <el-button :size="global.gSize" type="primary" @click.native="submitForm">{{ $t('action.submit') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import PopupTreeInput from "@/components/PopupTreeInput"
import KtDeleteButton from "@/views/Core/KtDeleteButton"
import KtButton from "@/views/Core/KtButton"
import { format } from "@/utils/datetime"
import UploadFile from "@/views/Core/UploadFile"
import SReflash from "@/components/Kj/SReflash"
import SQuery from "@/components/Kj/SQuery"
import { dictsFormat, getItemName } from "@/utils/myUtil"
import MyTable from "@/views/Core/MyTable"
import Column from "@/views/Core/Column"
import SDictForm from "@/components/Kj/SDictForm"
export default {
  components: {
    PopupTreeInput,
    MyTable,
    KtButton, KtDeleteButton,
    SReflash, SQuery, Column,
    UploadFile, SDictForm
  },

  data() {

    return {

      loading: false,
      filters: {
        name: '', pageNum: 1, pageSize: this.global.pageSize
      },
      unitsthis: {},
      percentageValue: 0,
      pageResult: {},
      tableData: [],
      componentKey: 0,
      operation: false, // true:新增, false:编辑
      dialogVisible: false, // 新增编辑界面是否显示
      UpLoadFileVisible: false,
      editLoading: false,
      // 新增编辑界面数据
      dataForm: {
        id: 0,

        orderNo: 1
      },
      classTypes: [],
    }
  },

  computed: {
    dataFormRules() {
      const dataFormRules = {
        name: [{ required: true, message: "请输入名称", trigger: 'blur' }],
        code: [{ required: true, message: "请输入编码", trigger: 'blur' }],
      };
      return dataFormRules;
    }
  },

  methods: {
    //获取分页数据
    findPage: function (data) {
      if (data != -1) {
        this.filters.pageNum = data
      }
      this.loading = true;
      this.$api.item.findPage(this.filters).then((res) => {
        this.pageResult = res.data
        this.loading = false;
      })
    },

    importExcel() {
      this.componentKey += 1;
      this.UpLoadFileVisible = true
    },
    ImportExcelData(excelData) {
      // 将上面数据转换成 table需要的数据
      let arr = [];
      excelData.forEach(item => {
        let obj = {};
        obj.code = item["编码"];
        obj.name = item["名称"];
        obj.gg = item["规格型号"];
        for (let i = 0; i < this.unitsthis.length; i++) {
          if (this.unitsthis[i].label == item["单位"]) {
            obj.unit = this.unitsthis[i].value
          }
        }
        //obj.unit = d.dicst[item["单位"]];
        obj.classifyId = item["物料类别"];
        obj.active = item["活动"];
        arr.push(obj);
        this.percentageValue = Math.round(this.percentageValue + 100 / excelData.length)
      });
      this.$api.item.ImportList(arr).then((res) => {
        if (res.code == 200) {
          this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
          this.UpLoadFileVisible = false
          this.findPage(-1)
          this.percentageValue = 0
        }
        else {
          this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
          this.UpLoadFileVisible = false
          this.percentageValue = 0
        }

      })


    },
    cancel: function () {
      this.UpLoadFileVisible = false;
      this.percentageValue = 0
    },
    //导出的方法
    exportExcel(xlsExport) {
      this.$api.item.GetExportList(this.filters).then((res) => {
        const tHeader = ['编码', '名称', '规格型号', '单位', '物料类别', '活动'];
        const filterVal = ['code', 'name', 'gg', 'unit', 'classifyId', 'active'];
        xlsExport(tHeader, filterVal, res.data, '物料信息导出');
      })

    },

    // 批量删除
    handleDelete: function (data) {
      this.$api.item.batchDelete(data.params)
    },
    // 显示新增界面
    handleAdd: function () {

      this.dialogVisible = true
      this.operation = true
      this.dataForm = {

      }
    },
    margin: function (row, column, cellValue, index) {
      return row.name + "   /   " + row.gg + ""
    },
    selectionFormats: function (row, column, cellValue, index) {
      let key = column.property;
      return dictsFormat(key, cellValue)
    },

    // 显示编辑界面
    handleEdit: function (index, row) {

      this.dialogVisible = true
      this.operation = false
      this.dataForm = Object.assign({}, row)
    },
    //取消
    cancelForm: function () {
      if (this.$refs['dataForm'] != undefined) {
        this.$refs['dataForm'].resetFields();
      }

      this.dialogVisible = false
    },
    //新增
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm(this.getKey('action.isConfirm'), this.getKey('action.tips'), {}).then(() => {
            this.editLoading = true
            let params = Object.assign({}, this.dataForm)
            this.$api.item.save(params).then((res) => {
              //this.editLoading = false
              if (res.code == 200) {
                this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
                this.dialogVisible = false
                this.$refs['dataForm'].resetFields()
              } else {
                this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
              }
              this.findPage(-1)
            })
          })
        }
      })
    },
    //`恢复
    handleRestore: function (index, row) {
      this.dataForm = Object.assign({}, row)
      if (this.dataForm.active == "正常") {
        this.$confirm('你选中的物料已经是正常状态了', '提示', {
          type: 'warning'
        })
      } else {
        this.dataForm.active = 1;
        this.$api.item.restore(this.dataForm).then((res) => {
          if (res.code == 200) {
            this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
            this.dialogVisible = false
          } else {
            this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
          }
          this.findPage(-1)
        })
      }
    },

    handleInitArea: function (index, row) {
      this.dataForm = Object.assign({}, row)

      this.dataForm.active = 1;
      this.$api.item.initArea(this.dataForm).then((res) => {
        if (res.code == 200) {
          this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
          this.dialogVisible = false
        } else {
          this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
        }
        this.findPage(-1)
      })

    },
    handleDisable: function (index, row) {
      this.dataForm = Object.assign({}, row)
      if (this.dataForm.active == "禁用") {
        this.$confirm('你选中的物料已经是禁用状态了', '提示', {
          type: 'warning'
        })
      } else {
        this.dataForm.active = 0;
        this.$api.item.disable(this.dataForm).then((res) => {
          if (res.code == 200) {
            this.$message({ message: this.getKey('action.operateSucess'), type: 'success' })
            this.dialogVisible = false
          } else {
            this.$message({ message: this.getKey('action.operateFail') + res.msg, type: 'error' })
          }
          this.findPage(-1)
        })
      }
    },

    // 时间格式化
    dateFormat: function (row, column, cellValue, index) {
      return format(row[column.property])
    },


    // 处理表格列过滤显示

    getKey: function (arg) {
      return this.$t(arg)
    },

    fenleiFormat: function (row, column, cellValue, index) {
      return dictsFormat("fenlei", cellValue)
    },

    activeStatusFormat: function (row, column, cellValue, index) {
      return dictsFormat("itemActive", cellValue)
    },
    classTypeToId: function (name) {
      let list = this.classTypes;
      for (let i = 0; i < list.length; i++) {
        if (list[i].name == name) {
          return list[i].id;
        }
      }
      return 0
    },
    selectionClassTypesFormats: function (row, column, cellValue, index) {
      let key = ""
      let propt = column.property;
      let val = row[column.property];
      let dict = this.classTypes;
      for (let i = 0; i < dict.length; i++) {
        if (dict[i].id == val) {
          return dict[i].name;
        }
      }
      return row[column.property]
    },
    lableToVal: function (name) {
   
      for (let i = 0; i < unitsthis.length; i++) {
        if (unitsthis[i].label == name) {
          return unitsthis[i].value;
        }
      }
    },

    dicToId: function (name) {

      return dictsFormat("coreItemType", name)
    },
 

    selectionFormat1: function (row, column, val, index) {

      return dictsFormat("itemSorting", val)

    },
  },


  created() {
    var d = this.$store.state.dict;
    this.unitsthis = d.dicts["units"];

    this.$api.classify.findPage().then((res) => {
      this.classTypes = res.data.content
    })


    this.findPage(1);
  },
  watch: {
    $UpLoadFileVisible(to, from) {
      console.log(to);
      console.log(from);
    },
    dialogVisible(to, from) {
      if (this.$refs['dataForm'] !== undefined) {
        this.$refs["dataForm"].resetFields();
      }
    }
  }
}

</script>

<style scoped></style>